package com.xjrsoft.module.base.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.Enum.EnabledMarkEnum;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageInput;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.core.tool.utils.BeanUtil;
import com.xjrsoft.core.tool.utils.StringPool;
import com.xjrsoft.core.tool.utils.StringUtil;
import com.xjrsoft.module.base.entity.XjrBaseDesktopscheme;
import com.xjrsoft.module.base.entity.XjrBaseDesktopschemeinfo;
import com.xjrsoft.module.base.entity.XjrBaseModule;
import com.xjrsoft.module.base.entity.XjrBaseSubsystem;
import com.xjrsoft.module.base.mapper.XjrBaseDesktopschemeMapper;
import com.xjrsoft.module.base.service.IXjrBaseDesktopschemeService;
import com.xjrsoft.module.base.service.IXjrBaseDesktopschemeinfoService;
import com.xjrsoft.module.base.service.IXjrBaseModuleService;
import com.xjrsoft.module.base.service.IXjrBaseRoleService;
import com.xjrsoft.module.base.vo.DesktopSchemeVo;
import com.xjrsoft.module.language.entity.XjrLgMark;
import com.xjrsoft.module.language.service.IXjrLgMarkService;
import com.xjrsoft.module.visual.entity.XjrVisualHomeRelation;
import com.xjrsoft.module.visual.entity.XjrVisualRelease;
import com.xjrsoft.module.visual.entity.XjrVisualReleaseRelation;
import com.xjrsoft.module.visual.service.IXjrVisualHomeRelationService;
import com.xjrsoft.module.visual.service.IXjrVisualReleaseRelationService;
import com.xjrsoft.module.visual.service.IXjrVisualReleaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zwq
 * @since 2021-12-01
 */
@Service
public class XjrBaseDesktopschemeServiceImpl extends ServiceImpl<XjrBaseDesktopschemeMapper, XjrBaseDesktopscheme> implements IXjrBaseDesktopschemeService {


    @Autowired
    private IXjrBaseDesktopschemeinfoService desktopschemeinfoService;


    @Autowired
    private IXjrLgMarkService lgMarkService;

    @Autowired
    private IXjrVisualReleaseService visualReleaseService;

    @Autowired
    private IXjrVisualReleaseRelationService visualReleaseRelationService;

    @Autowired
    private IXjrVisualHomeRelationService visualHomeRelationService;

    @Autowired
    private IXjrBaseRoleService roleService;

    @Autowired
    private IXjrBaseModuleService moduleService;

    @Autowired
    private XjrBaseSubsystemServiceImpl subsystemService;

    @Override
    public PageOutput<DesktopSchemeVo> getList(PageInput pageInput) {
        List<XjrLgMark> lgMarkList = lgMarkService.list();
        IPage<XjrBaseDesktopscheme> page = this.page(ConventPage.getPage(pageInput), Wrappers.<XjrBaseDesktopscheme>query().lambda().like(StringUtil.isNotBlank(pageInput.getKeyword()), XjrBaseDesktopscheme::getName, pageInput.getKeyword()));
        List<XjrBaseDesktopscheme> records = page.getRecords();
        List<DesktopSchemeVo> desktopSchemeVos = BeanUtil.copyList(records, DesktopSchemeVo.class);
        for (DesktopSchemeVo desktopSchemeVo : desktopSchemeVos) {
            //添加翻译标记名
            String lgMarkCode = desktopSchemeVo.getLgMarkCode();
            Optional<XjrLgMark> lgMarkOption = lgMarkList.stream().filter(s -> StringUtil.equals(s.getEnCode(), lgMarkCode)).findFirst();
            if (lgMarkOption.isPresent()) {
                desktopSchemeVo.setLgMarkName(lgMarkOption.get().getName());
            }
            String moduleId = desktopSchemeVo.getModuleId();
            XjrBaseModule module = moduleService.getById(moduleId);
            if (module != null) {
                desktopSchemeVo.setComponent(module.getComponent());
                desktopSchemeVo.setTarget(module.getTarget());
            }
        }
        PageOutput<DesktopSchemeVo> output = new PageOutput<>();
        output.setTotal(Convert.toInt(page.getTotal()));
        output.setRows(desktopSchemeVos);
        return output;
    }

    @Override
    public boolean add(JSONObject jsonObject) {
        JSONObject desktopSchemeJson = jsonObject.getJSONObject("desktopScheme");
        JSONArray desktopSchemeinfoJson = jsonObject.getJSONArray("desktopSchemeinfo");
        XjrBaseDesktopscheme xjrBaseDesktopscheme = JSONObject.parseObject(JSON.toJSONString(desktopSchemeJson), XjrBaseDesktopscheme.class);
        xjrBaseDesktopscheme.setLgMarkCode(desktopSchemeJson.getString("F_LgMarkCode"));
        String subSystemId = desktopSchemeJson.getString("F_SubSystemId");
        xjrBaseDesktopscheme.setSubSystemId(subSystemId);
        String moduleId = null;
        if (xjrBaseDesktopscheme.getIsMenu() == 1) {
            //是否发布成菜单
            XjrBaseModule module = BeanUtil.copy(xjrBaseDesktopscheme, XjrBaseModule.class);
            module.setFullName(xjrBaseDesktopscheme.getName());
            module.setEnCode(xjrBaseDesktopscheme.getCode());
            module.setParentId(xjrBaseDesktopscheme.getPModuleId());
            module.setSubSystemId(xjrBaseDesktopscheme.getSubSystemId());
            module.setEnabledMark(xjrBaseDesktopscheme.getIsMenu());
            module.setUrlAddress(StringPool.SLASH + "autoTemplates" + StringPool.SLASH + module.getEnCode() + StringPool.SLASH + moduleId);
            if (StringUtil.isEmpty(module.getParentId())) {
                module.setParentId(StringPool.ZERO);
            }
            moduleService.save(module);
            moduleId = module.getModuleId();
        }
        String desktopschemeId = StringUtil.randomUUID();
        String urlAddress = "/desktop-scheme/contentById/" + desktopschemeId;
        XjrBaseSubsystem xjrBaseSubsystem = subsystemService.getById(subSystemId);
        if (xjrBaseSubsystem != null && xjrBaseDesktopscheme.getIsFirst() == 1 && xjrBaseDesktopscheme.getEnabledMark() == 1) {
            //子系统首页
            xjrBaseSubsystem.setIndexUrl(urlAddress);
            subsystemService.updateById(xjrBaseSubsystem);
        }
        xjrBaseDesktopscheme.setId(desktopschemeId);
        xjrBaseDesktopscheme.setModuleId(moduleId);
        xjrBaseDesktopscheme.setUrlAddress(urlAddress);
        xjrBaseDesktopscheme.setIsDefault(0);
        if (this.save(xjrBaseDesktopscheme)) {
            //添加历史数据
            XjrBaseDesktopschemeinfo xjrBaseDesktopschemeinfo = new XjrBaseDesktopschemeinfo();
            xjrBaseDesktopschemeinfo.setSchemeId(desktopschemeId);
            xjrBaseDesktopschemeinfo.setContent(JSON.toJSONString(desktopSchemeinfoJson));
            if (desktopschemeinfoService.save(xjrBaseDesktopschemeinfo)) {
                //添加看板
                XjrVisualRelease visualRelease = BeanUtil.copy(xjrBaseDesktopscheme, XjrVisualRelease.class);
                visualRelease.setFullName(xjrBaseDesktopscheme.getName());
                visualRelease.setEnCode(xjrBaseDesktopscheme.getCode());
                visualRelease.setParentId(xjrBaseDesktopscheme.getPModuleId());
                visualRelease.setKanBanId(xjrBaseDesktopscheme.getId());
                visualRelease.setIndexs(xjrBaseDesktopscheme.getIsFirst());
                visualRelease.setCategory(2);
                return visualReleaseService.save(visualRelease);
            }
        }
        return false;
    }

    @Override
    public boolean update(JSONObject jsonObject) {
        JSONObject desktopSchemeJson = jsonObject.getJSONObject("desktopScheme");
        JSONArray desktopSchemeinfoJson = jsonObject.getJSONArray("desktopSchemeinfo");
        XjrBaseDesktopscheme xjrBaseDesktopscheme = JSONObject.parseObject(JSON.toJSONString(desktopSchemeJson), XjrBaseDesktopscheme.class);
        xjrBaseDesktopscheme.setLgMarkCode(desktopSchemeJson.getString("F_LgMarkCode"));
        String subSystemId = desktopSchemeJson.getString("F_SubSystemId");
        xjrBaseDesktopscheme.setSubSystemId(subSystemId);
        String moduleId = xjrBaseDesktopscheme.getModuleId();
        XjrBaseModule module = moduleService.getById(moduleId);
        if (module == null) {
            moduleId = StringUtil.randomUUID();
        }
        module = BeanUtil.copy(xjrBaseDesktopscheme, XjrBaseModule.class);
        module.setModuleId(moduleId);
        module.setFullName(xjrBaseDesktopscheme.getName());
        module.setEnCode(xjrBaseDesktopscheme.getCode());
        module.setParentId(xjrBaseDesktopscheme.getPModuleId());
        module.setSubSystemId(xjrBaseDesktopscheme.getSubSystemId());
        module.setEnabledMark(xjrBaseDesktopscheme.getIsMenu());
        module.setIsMenu(xjrBaseDesktopscheme.getIsMenu());
        module.setUrlAddress(StringPool.SLASH + "autoTemplates" + StringPool.SLASH + module.getEnCode() + StringPool.SLASH + moduleId);
        moduleService.saveOrUpdate(module);
        XjrBaseSubsystem xjrBaseSubsystem = subsystemService.getById(subSystemId);
        if (xjrBaseSubsystem != null && xjrBaseDesktopscheme.getIsFirst() == 1 && xjrBaseDesktopscheme.getEnabledMark() == 1) {
            //子系统首页
            xjrBaseSubsystem.setIndexUrl(xjrBaseDesktopscheme.getUrlAddress());
            subsystemService.updateById(xjrBaseSubsystem);
        }
        xjrBaseDesktopscheme.setModuleId(moduleId);
        if (this.updateById(xjrBaseDesktopscheme)) {
            //添加一条历史数据
            XjrBaseDesktopschemeinfo one = desktopschemeinfoService.getOne(Wrappers.<XjrBaseDesktopschemeinfo>query().lambda().eq(XjrBaseDesktopschemeinfo::getSchemeId, xjrBaseDesktopscheme.getId()).eq(XjrBaseDesktopschemeinfo::getEnabledMark, EnabledMarkEnum.ENABLED.getCode()));
            one.setEnabledMark(EnabledMarkEnum.NOENABLED.getCode());
            if (desktopschemeinfoService.updateById(one)) {
                XjrBaseDesktopschemeinfo xjrBaseDesktopschemeinfo = new XjrBaseDesktopschemeinfo();
                xjrBaseDesktopschemeinfo.setSchemeId(xjrBaseDesktopscheme.getId());
                xjrBaseDesktopschemeinfo.setContent(JSON.toJSONString(desktopSchemeinfoJson));
                if (desktopschemeinfoService.save(xjrBaseDesktopschemeinfo)) {
                    //更新看板
                    XjrVisualRelease visualRelease = BeanUtil.copy(xjrBaseDesktopscheme, XjrVisualRelease.class);
                    visualRelease.setFullName(xjrBaseDesktopscheme.getName());
                    visualRelease.setEnCode(xjrBaseDesktopscheme.getCode());
                    visualRelease.setParentId(xjrBaseDesktopscheme.getPModuleId());
                    visualRelease.setKanBanId(xjrBaseDesktopscheme.getId());
                    visualRelease.setIndexs(xjrBaseDesktopscheme.getIsFirst());
                    visualRelease.setCategory(2);
                    visualReleaseService.update(visualRelease);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean delete(String id) throws Exception {
        XjrBaseDesktopscheme xjrBaseDesktopscheme = this.getById(id);
        if (xjrBaseDesktopscheme == null) {
            throw new Exception("此条记录不存在");
        }
        if (this.removeById(id)) {
            //删除历史记录
            if (desktopschemeinfoService.remove(Wrappers.<XjrBaseDesktopschemeinfo>query().lambda().eq(XjrBaseDesktopschemeinfo::getSchemeId, id))) {
                //删除看板和菜单
                moduleService.removeById(xjrBaseDesktopscheme.getModuleId());
                XjrVisualRelease xjrVisualRelease = visualReleaseService.getOne(Wrappers.<XjrVisualRelease>query().lambda().eq(XjrVisualRelease::getKanBanId, id));
                if(xjrVisualRelease!=null) {
                    String visualReleaseId = xjrVisualRelease.getId();
                    visualReleaseService.removeById(visualReleaseId);
                    visualReleaseRelationService.remove(Wrappers.<XjrVisualReleaseRelation>query().lambda().eq(XjrVisualReleaseRelation::getVisualReleaseId,visualReleaseId));
                    visualHomeRelationService.remove(Wrappers.<XjrVisualHomeRelation>query().lambda().eq(XjrVisualHomeRelation::getVisualReleaseId,visualReleaseId));
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public JSONObject getDesktopschemeById(String id) throws Exception {
        XjrBaseDesktopscheme xjrBaseDesktopscheme = this.getById(id);
        if (xjrBaseDesktopscheme == null) {
            throw new Exception("桌面设计模板不存在!");
        }
        XjrBaseDesktopschemeinfo destopSchemeinfo = desktopschemeinfoService.getOne(Wrappers.<XjrBaseDesktopschemeinfo>query().lambda().eq(XjrBaseDesktopschemeinfo::getSchemeId, id).eq(XjrBaseDesktopschemeinfo::getEnabledMark, EnabledMarkEnum.ENABLED.getCode()));
        DesktopSchemeVo desktopSchemeVo = BeanUtil.copy(xjrBaseDesktopscheme, DesktopSchemeVo.class);
        JSONObject resultJson = new JSONObject();
        resultJson.put("desktopScheme", JSONObject.parseObject(JSON.toJSONString(desktopSchemeVo, SerializerFeature.WriteMapNullValue)));
        resultJson.put("desktopSchemeinfo", JSONArray.parseArray(destopSchemeinfo.getContent()));
        return resultJson;
    }

    @Override
    public boolean copy(String id) throws Exception {
        XjrBaseDesktopscheme xjrBaseDesktopscheme = this.getById(id);
        XjrBaseDesktopschemeinfo xjrBaseDesktopschemeinfo = desktopschemeinfoService.getOne(Wrappers.<XjrBaseDesktopschemeinfo>query().lambda().eq(XjrBaseDesktopschemeinfo::getSchemeId, id).eq(XjrBaseDesktopschemeinfo::getEnabledMark, EnabledMarkEnum.ENABLED.getCode()));
        if (xjrBaseDesktopscheme == null) {
            throw new Exception("桌面设计模板不存在!");
        }
        String moduleId = null;
        if (xjrBaseDesktopscheme.getIsMenu() == 1) {
            //是否发布成菜单
            moduleId = StringUtil.randomUUID();
            XjrBaseModule module = BeanUtil.copy(xjrBaseDesktopscheme, XjrBaseModule.class);
            module.setModuleId(moduleId);
            module.setFullName(xjrBaseDesktopscheme.getName());
            module.setEnCode(xjrBaseDesktopscheme.getCode());
            module.setParentId(xjrBaseDesktopscheme.getPModuleId());
            module.setSubSystemId(xjrBaseDesktopscheme.getSubSystemId());
            module.setEnabledMark(xjrBaseDesktopscheme.getIsMenu());
            module.setUrlAddress(StringPool.SLASH + "autoTemplates" + StringPool.SLASH + module.getEnCode() + StringPool.SLASH + moduleId);
            if (StringUtil.isEmpty(module.getParentId())) {
                module.setParentId(StringPool.ZERO);
            }
            moduleService.save(module);
        }
        String desktopschemeId = StringUtil.randomUUID();
        String urlAddress = "/desktop-scheme/contentById/" + desktopschemeId;
        XjrBaseSubsystem xjrBaseSubsystem = subsystemService.getById(xjrBaseDesktopscheme.getSubSystemId());
        if (xjrBaseSubsystem != null && xjrBaseDesktopscheme.getIsFirst() == 1 && xjrBaseDesktopscheme.getEnabledMark() == 1) {
            //子系统首页
            xjrBaseSubsystem.setIndexUrl(urlAddress);
            subsystemService.updateById(xjrBaseSubsystem);
        }
        xjrBaseDesktopscheme.setId(desktopschemeId);
        xjrBaseDesktopscheme.setModuleId(moduleId);
        xjrBaseDesktopscheme.setUrlAddress(urlAddress);
        xjrBaseDesktopscheme.setCreateDate(LocalDateTime.now());
        xjrBaseDesktopscheme.setCreateUserId(SecureUtil.getUserId());
        xjrBaseDesktopscheme.setCreateUserName(SecureUtil.getUserName());
        xjrBaseDesktopscheme.setIsDefault(0);
        if (this.save(xjrBaseDesktopscheme)) {
            xjrBaseDesktopschemeinfo.setId(StringUtil.randomUUID());
            xjrBaseDesktopschemeinfo.setSchemeId(desktopschemeId);
            xjrBaseDesktopschemeinfo.setCreateDate(LocalDateTime.now());
            xjrBaseDesktopschemeinfo.setCreateUserId(SecureUtil.getUserId());
            xjrBaseDesktopschemeinfo.setCreateUserName(SecureUtil.getUserName());
            if (desktopschemeinfoService.save(xjrBaseDesktopschemeinfo)) {
                //添加看板
                XjrVisualRelease visualRelease = BeanUtil.copy(xjrBaseDesktopscheme, XjrVisualRelease.class);
                visualRelease.setFullName(xjrBaseDesktopscheme.getName());
                visualRelease.setEnCode(xjrBaseDesktopscheme.getCode());
                visualRelease.setParentId(xjrBaseDesktopscheme.getPModuleId());
                visualRelease.setKanBanId(xjrBaseDesktopscheme.getId());
                visualRelease.setIndexs(xjrBaseDesktopscheme.getIsFirst());
                visualRelease.setCategory(2);
                return visualReleaseService.save(visualRelease);
            }
        }
        return false;
    }

    @Override
    public boolean setDefault(String id) throws Exception {
        //查看当前设置为默认的桌面设计
        XjrBaseDesktopscheme oldDesktopscheme = this.getOne(Wrappers.<XjrBaseDesktopscheme>query().lambda().eq(XjrBaseDesktopscheme::getIsDefault, 1));
        if (oldDesktopscheme != null) {
            if (StringUtil.equals(id, oldDesktopscheme.getId())) {
                throw new Exception("已设置为默认首页");
            }
            oldDesktopscheme.setIsDefault(0);
            if(this.updateById(oldDesktopscheme)){
                //删除首页授权相关的数据
                XjrVisualRelease visualRelease = visualReleaseService.getOne(Wrappers.<XjrVisualRelease>query().lambda().eq(XjrVisualRelease::getKanBanId, oldDesktopscheme.getId()));
                if(visualRelease!=null){
                    visualReleaseRelationService.remove(Wrappers.<XjrVisualReleaseRelation>query().lambda().eq(XjrVisualReleaseRelation::getVisualReleaseId,visualRelease.getId()));
                    visualHomeRelationService.remove(Wrappers.<XjrVisualHomeRelation>query().lambda().eq(XjrVisualHomeRelation::getVisualReleaseId,visualRelease.getId()));
                }
            }
        }
        XjrBaseDesktopscheme xjrBaseDesktopscheme = this.getById(id);
        if (xjrBaseDesktopscheme != null) {
            xjrBaseDesktopscheme.setIsDefault(1);
            if(this.updateById(xjrBaseDesktopscheme)) {
                XjrVisualRelease visualRelease = visualReleaseService.getOne(Wrappers.<XjrVisualRelease>query().lambda().eq(XjrVisualRelease::getKanBanId, xjrBaseDesktopscheme.getId()));
                if(visualRelease!=null) {
                    visualReleaseRelationService.remove(Wrappers.<XjrVisualReleaseRelation>query().lambda().eq(XjrVisualReleaseRelation::getVisualReleaseId,visualRelease.getId()));
                    visualHomeRelationService.remove(Wrappers.<XjrVisualHomeRelation>query().lambda().eq(XjrVisualHomeRelation::getVisualReleaseId,visualRelease.getId()));
                    //添加首页授权数据
                        XjrVisualReleaseRelation xjrVisualReleaseRelation = new XjrVisualReleaseRelation();
                        xjrVisualReleaseRelation.setCategory(1);
                        xjrVisualReleaseRelation.setObjectId("defaultCurrent");
                        xjrVisualReleaseRelation.setVisualReleaseId(visualRelease.getId());
                    if(visualReleaseRelationService.save(xjrVisualReleaseRelation)){
                        XjrVisualHomeRelation xjrVisualHomeRelation = new XjrVisualHomeRelation();
                        xjrVisualHomeRelation.setUserId("defaultCurrent");
                        xjrVisualHomeRelation.setVisualReleaseId(visualRelease.getId());
                       return visualHomeRelationService.save(xjrVisualHomeRelation);
                    }
                }
            }
        }
        return false;
    }
}
